<!-- <template>
  <div class="login">
    <h1>{{ formType === 'login' ? '登录' : '注册' }}</h1>
    <input v-model="username" placeholder="用户名/邮箱（例如111@qq.com）" type="text" />
    <input v-model="password" placeholder="密码" type="password" />
    <input v-if="formType === 'register'" v-model="confirmPassword" placeholder="确认密码" type="password" />

    <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
    <p v-if="successMessage" class="success-message">{{ successMessage }}</p>

    <div class="button-group">
      <el-button 
        :type="formType === 'login' ? 'success' : 'primary'" 
        @click="handleFormSubmit"
        :loading="loading"
      >
        {{ formType === 'login' ? '登录' : '注册' }}
      </el-button>
      <el-button 
        type="text" 
        @click="toggleForm"
      >
        {{ formType === 'login' ? '去注册' : '去登录' }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useUserStore } from '../stores/user';
import { useRouter } from 'vue-router';
import { login, reg } from '../utils/request';

// 定义响应式变量
const username = ref<string>('');
const password = ref<string>('');
const confirmPassword = ref<string>('');
const userStore = useUserStore();
const router = useRouter();
const formType = ref<'login' | 'register'>('login');
const errorMessage = ref<string>('');
const successMessage = ref<string>('');
const loading = ref<boolean>(false);

// 表单验证函数
const validateForm = (): boolean => {
  errorMessage.value = '';

  if (!username.value || !password.value) {
    errorMessage.value = '用户名和密码不能为空';
    return false;
  }

  if (formType.value === 'register') {
    if (password.value !== confirmPassword.value) {
      errorMessage.value = '两次输入的密码不一致';
      return false;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(username.value)) {
      errorMessage.value = '请输入有效的邮箱地址';
      return false;
    }
  }

  return true;
};

// 登录API调用函数
const loginWithApi = async (credentials: { username: string; pwd: string }) => {
  try {
    const result = await login(credentials);
    if (result) {
      return result;
    }
    errorMessage.value = '账号或密码错误';
    return null;
  } catch (error) {
    console.error('登录错误:', error);
    errorMessage.value = '登录失败，请检查网络连接或重试';
    return null;
  }
};

// 注册API调用函数
const registerWithApi = async (userData: { email: string; password: string }) => {
  try {
    const result = await reg(userData);
    if (result && result.errno === 0) {
      return result.data;
    }
    errorMessage.value = result?.message || '注册失败，请重试';
    return null;
  } catch (error) {
    console.error('注册错误:', error);
    errorMessage.value = '注册失败，请重试';
    return null;
  }
};

// 处理表单提交函数
const handleFormSubmit = async () => {
  if (!validateForm()) return;

  loading.value = true;

  try {
    if (formType.value === 'login') {
      const r = await loginWithApi({
        username: username.value,
        pwd: password.value
      });

      if (r) {
        sessionStorage.setItem('isLoggedIn', 'true');
        userStore.setUser(r);
        router.push('/todolist');
      }
    } else {
      const r = await registerWithApi({
        email: username.value,
        password: password.value
      });

      if (r) {
        successMessage.value = '注册成功！已自动填充账号密码，请登录';
        password.value = confirmPassword.value;

        setTimeout(() => {
          toggleForm();
          successMessage.value = '';
        }, 1500);
      }
    }
  } finally {
    loading.value = false;
  }
};

// 切换表单类型函数
const toggleForm = () => {
  errorMessage.value = '';
  successMessage.value = '';

  if (formType.value === 'register') {
    // 注册切登录时，保留用户名和密码
  } else {
    confirmPassword.value = '';
  }

  formType.value = formType.value === 'login' ? 'register' : 'login';
};
</script>

<style scoped>
.login {
  padding: 20px;
  text-align: center;
}

input {
  margin: 10px;
  padding: 10px;
  width: 200px;
}

button {
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #218838;
}

.error-message {
  color: red;
  margin: 5px 0;
}

.success-message {
  color: green;
  margin: 5px 0;
}

.button-group {
  margin-top: 20px;
}

.main-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style> -->






<template>
  <div class="auth-container" style="position: fixed;">
    <div v-if="isLogin">
      <h2>登录</h2>
      <div class="input-container">
        <input v-model="email" type="email" placeholder="用户名/邮箱" />
      </div>
      <div class="input-container">
        <input v-model="password" type="password" placeholder="密码" />
      </div>
      <div class="input-container">
        <button @click="btnLogin">登录</button>
      </div>
    </div>

    <div v-else>
      <h2>注册</h2>
      <div class="input-container">
        <input v-model="username" placeholder="用户名/邮箱" />
      </div>
      <div class="input-container">
        <input v-model="password" type="password" placeholder="密码" />
      </div>
      <div class="input-container">
        <input v-model="confirmPassword" type="password" placeholder="确认密码" />
      </div>
      <div class="input-container">
        <input v-model="realName" placeholder="姓名" />
      </div>
      <div class="input-container">
        <input v-model="stuNum" type="number" placeholder="学号" />
      </div>
      <div class="input-container">
        <input v-model="age" type="number" placeholder="年龄" />
      </div>
      <div class="input-container">
        <input v-model="email" type="email" placeholder="邮箱" />
      </div>
      <div class="input-container">
        <el-select v-model="className" placeholder="选择班级" size="large">
          <el-option :key="1" label="23软件技术1班" value="23软件技术1班" />
          <el-option :key="2" label="23软件技术2班" value="23软件技术2班" />
        </el-select>
      </div>
      <div class="input-container">
        <button @click="register">注册</button>
      </div>
    </div>

    <div class="toggle-buttons" style="margin-top: 20px;">
      <button :class="{ active: isLogin }" @click="isLogin = true">登录</button>
      <button :class="{ active: !isLogin }" @click="isLogin = false">注册</button>
    </div>

    <div class="home-link">
      <RouterLink to="/">返回首页</RouterLink>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';
import { login, reg } from '../utils/request';

const userStore = useUserStore();
const router = useRouter();

// 控制显示登录还是注册表单
const isLogin = ref(true);

const email = ref('');
const username = ref('');
const password = ref('');
const confirmPassword = ref('');
const age = ref();
const realName = ref('');
const stuNum = ref('');
const className = ref('23软件技术1班');

const btnLogin = async () => {
  const r = await login({
    username: email.value,
    pwd: password.value,
  });
  if (r) {
    sessionStorage.setItem('user', JSON.stringify(r)); // 存储用户信息到 sessionStorage
    userStore.setUser(r);
    router.push('/product');
  } else {
    alert('账号或密码错误');
  }
};

const register = async () => {
  // 注册逻辑
  if (password.value !== confirmPassword.value) {
    alert('两次输入的密码不一致');
    return;
  }
  const r = await reg({
    username: username.value,
    pwd: password.value,
    realName: realName.value,
    stuNum: stuNum.value,
    age: age.value,
    email: email.value,
    className: className.value,
  });
  console.log(r);
  if (r.errno) return alert(r.message);
  else router.push('/login');
};
</script>

<style scoped>
.auth-container {
  width: 30%;
  left: 50%;
  top: 50%; 
  transform: translate(-50%, -50%);
  padding: 20px;
  text-align: center;
  background-color: #f0f0f0;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.toggle-buttons {
  display: flex;
  justify-content: center;
  margin-bottom: 1.5rem;
  gap: 10px;
}

.toggle-buttons button {
  padding: 8px 16px;
  border: none;
  background-color: #e0e0e0;
  color: #333;
  cursor: pointer;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
}

.toggle-buttons button.active {
  background-color: #28a745;
  color: white;
}

.input-container {
  margin-bottom: 1rem;
}

.input-container input, 
.input-container el-select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.auth-link {
  display: block;
  margin-top: 1rem;
  color: #28a745;
  text-decoration: none;
  font-size: 0.9rem;
}

.auth-link:hover {
  text-decoration: underline;
}

.input-container button {
  width: 100%;
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
}

.input-container button:hover {
  background-color: #218838;
}

.home-link {
  margin-top: 1.5rem;
  font-size: 0.9rem;
}

.home-link a {
  color: #28a745;
  text-decoration: none;
  font-weight: bold;
}

.home-link a:hover {
  text-decoration: underline;
}
</style>